<template>
  <div class="login">
    <el-form ref="forgetFormRef" :model="forgetForm" :rules="forgetRules" class="login-form">
      <h3 class="title">重置密码</h3>
      <el-form-item prop="phone">
        <el-input v-model="forgetForm.phone" type="text" auto-complete="off" placeholder="账号" maxlength="11">
          <template #prefix><svg-icon icon-class="phone" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="forgetForm.password"
          type="password"
          auto-complete="off"
          show-password
          placeholder="请输入密码"
        >
          <template #prefix>
            <svg-icon icon-class="password" class="el-input__icon input-icon" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="forgetForm.password2"
          type="password"
          auto-complete="off"
          show-password
          placeholder="请再次输入密码"
        >
          <template #prefix>
            <svg-icon icon-class="password" class="el-input__icon input-icon" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input
          v-model="forgetForm.code"
          auto-complete="off"
          placeholder="请输入验证码"
          style="width: 63%"
          maxlength="4"
        >
          <template #prefix>
            <svg-icon icon-class="validCode" class="el-input__icon input-icon" />
          </template>
        </el-input>
        <div class="login-code">
          <el-button :loading="loading" :disabled="disabled" type="primary" class="login-code-button" @click="sendSMS">
            <span>{{
              codeTextShow === 0
                ? codeText.btntext
                : codeTextShow === 1
                ? count + codeText.countdown
                : codeText.getAgain
            }}</span>
          </el-button>
        </div>
      </el-form-item>
      <el-form-item style="width: 100%">
        <el-button :loading="loading" type="primary" class="login-btn" style="width: 100%" @click="submitForm()">
          <span v-if="!loading">重 置 密 码</span>
          <span v-else>重 置 密 码 中...</span>
        </el-button>
      </el-form-item>
      <el-form-item class="go-reg">
        <router-link to="/login">
          <span>去登录</span>
        </router-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
  import { resetPwd, getPhoneSMS } from '@/api/login';
  import { ref, watch, getCurrentInstance } from 'vue';
  import { useRoute, useRouter } from 'vue-router';

  const route = useRoute();
  const router = useRouter();
  const { proxy: $vm } = getCurrentInstance();
  const loading = ref(false);
  const redirect = ref(undefined);
  const disabled = ref(false);
  const codeTextShow = ref(0);
  const mobileCode = ref('');
  const count = ref(59);
  const forgetFormRef = ref(null);
  // 自定义验证
  const checkSendPassword = (rule, value, callback) => {
    if (value) {
      if (forgetForm.value.password !== value) {
        callback(new Error(rule.message));
      }
      callback();
    }
    callback(new Error(rule.message));
  };
  const forgetForm = ref({
    phone: '',
    code: '',
    password: '',
    password2: '',
    userType: route.query.type,
  });
  const codeText = ref({
    btntext: '发送验证码',
    countdown: 's后重发',
    getAgain: '重新获取',
  });
  const forgetRules = ref({
    phone: [
      {
        required: true,
        trigger: 'blur',
        message: '手机号不能为空',
      },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur',
      },
    ],
    password: [
      {
        required: true,
        trigger: 'blur',
        message: '密码不能为空',
      },
      {
        pattern: /(?!^\d+$)(?!^[A-Za-z]+$)(?!^[^A-Za-z0-9]+$)(?!^.*[\u4E00-\u9FA5].*$)^\S{8,}$/,
        message: '密码须含字母、数字符号至少两种组合，且密码长度不小于8',
      },
    ],
    password2: [
      {
        required: true,
        trigger: 'blur',
        message: '确认密码不能为空',
      },
      {
        validator: checkSendPassword, // You need to define this validator function
        message: '两次密码输入不一致',
        trigger: 'blur',
      },
    ],
    code: [
      {
        required: true,
        trigger: 'change',
        message: '验证码不能为空',
      },
    ],
  });

  watch(
    () => route,
    (route) => {
      redirect.value = route.query && route.query.redirect;
    },
    {
      immediate: true,
    },
  );

  function sendSMS() {
    forgetRules.value.code[0].required = false;
    /* Warn: Cannot find refs name */
    forgetFormRef.value.validate((valid) => {
      if (valid) {
        getPhoneSMS(forgetForm.value.phone).then((res) => {
          if (res.code === 200) {
            mobileCode.value = res.data;
            forgetRules.value.code[0].required = true;

            disabled.value = true;
            codeTextShow.value = 1;
            const interval = setInterval(() => {
              count.value--; // 倒计时计数自减
            }, 1000); // 每隔1秒变化一次
            setTimeout(() => {
              clearInterval(interval); // 清除定时器
              count.value = 59; // 第一轮结束后，再次点击获取，会从-1开始
              codeTextShow.value = 2; // 状态值等于2
              disabled.value = false; // 禁止按钮点击
            }, 60000);
          } else {
            /* Warn: Unknown source: $message */
            $vm.$message({
              message: res.msg,
              type: 'warning',
            });
          }
        });
      }
    });
  }

  function submitForm() {
    forgetFormRef.value.validate((valid) => {
      if (valid) {
        loading.value = true;
        const data = {
          phone: forgetForm.value.phone,
          pwd: forgetForm.value.password,
          checkCode: forgetForm.value.code,
          userType: route.query.type,
        };
        resetPwd(data)
          .then((res) => {
            loading.value = false;
            if (res.code === 200) {
              $vm.msgSuccess('修改成功');
              setTimeout(() => {
                router.push('/login');
              }, 2000);
            }
          })
          .catch((_) => {
            loading.value = false;
          });
      }
    });
  }
</script>

<style rel="scss" lang="scss">
  @import './public.scss';
</style>
